package com.changgou.seckill.consumer;

import com.alibaba.fastjson.JSON;
import com.changgou.seckill.pojo.SeckillStatus;
import com.changgou.seckill.service.SeckillOrderService;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

/**
 * @author 秦川熙
 */
@Component
@RabbitListener(queues = "${mq.pay.queue.seckillordertimer}")
public class SeckillOrderDelayMessageListener {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SeckillOrderService seckillOrderService;


    /**
     * 读取消息
     * 判断redis中是否存在对应的订单
     * 如果存在， 则关闭支付， 再关闭订单
     * @param message
     */
    @RabbitListener
    public void consumeMessage(@Payload String message) {
        try {
            //获取用户的排队信息
            SeckillStatus seckillStatus = JSON.parseObject(message, SeckillStatus.class);

            //如果此时redis中没有用户排队信息， 则表明该订单已经处理， 如果有用户排队信息， 则表示用户尚未完成支付， 关闭订单【关闭微信支付】
            Object userQueueStatus = redisTemplate.boundHashOps("UserQueueStatus").get(seckillStatus.getUsername());

            if (userQueueStatus != null) {
                //删除订单
                seckillOrderService.delete(seckillStatus.getGoodsId());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
